package cn.gp.chat.service;

import cn.gp.chat.commom.resp.MessageVo;
import cn.gp.chat.mapper.MessageMapper;
import cn.gp.chat.common.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageService {
    private static final int DEFAULT_LIMIT = 50;
    private final MessageMapper messageMapper;
    
    public ApiResponse<Void> saveMessage(MessageVo messageVo) {
        // 检查是否是好友关系
        if (!isFriends(messageVo.getSenderId(), messageVo.getReceiverId())) {
            return ApiResponse.fail(400, "只能给好友发送消息");
        }

        // 设置默认值
        if (messageVo.getContentType() == null) {
            messageVo.setContentType(1);  // 默认为文本消息
        }
        if (messageVo.getStatus() == null) {
            messageVo.setStatus(0);  // 默认为发送中状态
        }
        
        try {
            messageMapper.insert(messageVo);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("保存消息失败", e);
            return ApiResponse.fail(500, "保存消息失败: " + e.getMessage());
        }
    }

    private boolean isFriends(Long userId1, Long userId2) {
        return messageMapper.checkFriendship(userId1, userId2) > 0;
    }

    public ApiResponse<List<MessageVo>> getChatHistory(Long userId1, Long userId2, Integer limit) {
        try {
            // 使用默认值50，如果传入的limit大于50则使用50
            int actualLimit = (limit == null || limit > DEFAULT_LIMIT) ? DEFAULT_LIMIT : limit;
            List<MessageVo> messageVos = messageMapper.getChatHistory(userId1, userId2, actualLimit);
            log.info("获取到聊天历史记录数量: {}", messageVos.size());
            return ApiResponse.success(messageVos);
        } catch (Exception e) {
            log.error("获取聊天历史失败", e);
            return ApiResponse.fail(500, "获取聊天历史失败: " + e.getMessage());
        }
    }

    public MessageVo getMessageById(Long id) {
        try {
            return messageMapper.getMessageById(id);
        } catch (Exception e) {
            log.error("获取消息失败, id={}", id, e);
            return null;
        }
    }
} 